import tkinter as tk
from tkinter import ttk, messagebox, simpledialog
import json

from score_info import ScoreInfo
"""学生成绩后台业务实现：数据状态存储csv文件中"""
class ScoreWindow:
    def __init__(self, root):
        self.root = root
        self.root.title("学生成绩管理")

        # 初始化数据
        # self.data = [
        #     {"id_no": 9001, "name": "张飞", "course": "语言", "score": 90, "cls": "科创一班", "year": 2022},
        #     {"id_no": 9002, "name": "关羽", "course": "数学", "score": 85, "cls": "科创二班", "year": 2023},
        #     {"id_no": 9003, "name": "赵云", "course": "英语", "score": 92, "cls": "科创一班", "year": 2022},
        #     {"id_no": 9004, "name": "马超", "course": "物理", "score": 88, "cls": "科创三班", "year": 2023},
        #     {"id_no": 9005, "name": "黄忠", "course": "化学", "score": 95, "cls": "科创二班", "year": 2022}
        # ]
        # 从score_data.csv文件中读取数据 @todo
        self.data = ScoreInfo.read_score_data()


        # 创建搜索框
        self.search_frame = ttk.Frame(root)
        self.search_frame.pack(pady=5)

        ttk.Label(self.search_frame, text="学生编号:").pack(side=tk.LEFT, padx=2)
        self.search_entry = ttk.Entry(self.search_frame, width=20)
        self.search_entry.pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_frame, text="搜索", command=self.search_data).pack(side=tk.LEFT, padx=2)

        # 创建表格
        self.tree = ttk.Treeview(root, columns=("id_no", "name", "course", "score", "cls", "year"), show="headings")
        self.tree.heading("id_no", text="学生编号")
        self.tree.heading("name", text="姓名")
        self.tree.heading("course", text="课程")
        self.tree.heading("score", text="成绩")
        self.tree.heading("cls", text="班级")
        self.tree.heading("year", text="年度")
        self.tree.pack(pady=5)

        # 按钮框架
        btn_frame = ttk.Frame(root)
        btn_frame.pack(pady=5)
        ttk.Button(btn_frame, text="新增", command=self.show_add_dialog).pack(side=tk.LEFT, padx=10)
        ttk.Button(btn_frame, text="修改", command=self.show_edit_dialog).pack(side=tk.LEFT, padx=10)
        ttk.Button(btn_frame, text="删除", command=self.delete_data).pack(side=tk.LEFT, padx=10)

        self.refresh_table()

    def refresh_table(self):
        for item in self.tree.get_children():
            self.tree.delete(item)
        for item in self.data:
            self.tree.insert("", "end", values=(
                item["id_no"], item["name"], item["course"],
                item["score"], item["cls"], item["year"]
            ))

    def search_data(self):
        search_id = self.search_entry.get()
        if not search_id:
            self.refresh_table()
            return
        filtered_data = [item for item in self.data if str(item["id_no"]) == search_id]
        self.data = filtered_data
        self.refresh_table()

    def show_add_dialog(self):
        dialog = tk.Toplevel(self.root)
        dialog.title("新增学生")

        fields = ["id_no", "name", "course", "score", "cls", "year"]
        col_dict={"id_no":"学生编号","name":"姓名","course":"课程","score":"成绩","cls":"班级","year":"年度"}
        entries = {}
        for i, field in enumerate(fields):
            #转换成相关对应的标签字段
            ttk.Label(dialog, text=col_dict[field]).grid(row=i, column=0, padx=2, pady=2)
            entries[field] = ttk.Entry(dialog)
            entries[field].grid(row=i, column=1, padx=2, pady=2)

        ttk.Button(dialog, text="确认", command=lambda: self.add_data(entries, dialog)).grid(row=6, columnspan=2,
                                                                                             pady=5)

    def add_data(self, entries, dialog):
        try:
            new_data = {
                "id_no": int(entries["id_no"].get()),
                "name": entries["name"].get(),
                "course": entries["course"].get(),
                "score": int(entries["score"].get()),
                "cls": entries["cls"].get(),
                "year": int(entries["year"].get())
            }
            self.data.append(new_data)
            dialog.destroy()
            self.refresh_table()
            #  把内存数据写入到文件中,采用csv格式 @todo
            ScoreInfo.write_score_data(self.data)


        except ValueError:
            messagebox.showerror("错误", "输入数据格式错误")

    def show_edit_dialog(self):
        selected = self.tree.selection()
        if not selected:
            messagebox.showwarning("提示", "请选择要修改的行")
            return

        item = self.tree.item(selected[0])
        data = {
            "id_no": item["values"][0],
            "name": item["values"][1],
            "course": item["values"][2],
            "score": item["values"][3],
            "cls": item["values"][4],
            "year": item["values"][5]
        }

        dialog = tk.Toplevel(self.root)
        dialog.title("修改学生")

        fields = ["id_no", "name", "course", "score", "cls", "year"]
        col_dict={"id_no":"学生编号","name":"姓名","course":"课程","score":"成绩","cls":"班级","year":"年度"}
        entries = {}
        for i, field in enumerate(fields):
            ttk.Label(dialog, text=col_dict[field]).grid(row=i, column=0, padx=2, pady=2)
            entries[field] = ttk.Entry(dialog)
            entries[field].insert(0, data[field])
            entries[field].grid(row=i, column=1, padx=2, pady=2)

        ttk.Button(dialog, text="确认", command=lambda: self.edit_data(entries, dialog, data["id_no"])).grid(row=6,
                                                                                                             columnspan=2,
                                                                                                             pady=5)

    def edit_data(self, entries, dialog, original_id):
        try:
            for item in self.data:
                if item["id_no"] == original_id:
                    item.update({
                        "id_no": int(entries["id_no"].get()),
                        "name": entries["name"].get(),
                        "course": entries["course"].get(),
                        "score": int(entries["score"].get()),
                        "cls": entries["cls"].get(),
                        "year": int(entries["year"].get())
                    })
                    break
            dialog.destroy()
            self.refresh_table()
            #  把内存数据写入到文件中,采用csv格式 @todo
            ScoreInfo.write_score_data(self.data)

        except ValueError:
            messagebox.showerror("错误", "输入数据格式错误")

    def delete_data(self):
        selected = self.tree.selection()
        if not selected:
            messagebox.showwarning("提示", "请选择要删除的行")
            return

        if messagebox.askyesno("确认", "确定要删除吗？"):
            item = self.tree.item(selected[0])
            id_no = int(item["values"][0])
            self.data = [item for item in self.data if item["id_no"] != id_no]
            self.refresh_table()
            #  把内存数据写入到文件中,采用csv格式 @todo
            ScoreInfo.write_score_data(self.data)



if __name__ == "__main__":
    root = tk.Tk()
    app = ScoreWindow(root)
    root.mainloop()